package com.youzi.mdtool.util;

import java.io.File;

import org.springframework.stereotype.Component;

import com.youzi.mdtool.entity.Catalog;

/**
 *  文件工具类
 * @author ：Andrew.Song
 * @Date : 2018-8-27 18:02
 */
@Component
public class FileUtil {

	private static int id=0;

    /**
     * 根据文件查询目录递归查询
     * @param filePath
     * @return
     */
	public Catalog iteratorFile(String filePath) {
		File file = new File(filePath);
		if(!file.exists()){
			return null;
		}
		Catalog catalog = new Catalog();
		catalog.setName(file.getName());
		catalog.setDir(true);
		catalog.setId(id++);
		catalog.setPath(file.getPath());
		catalog.setSpread(false);
		return iteratorChildFile(file.listFiles(),catalog);
	}
	

	private Catalog iteratorChildFile(File[] files, Catalog catalog){
		for (File file : files) {
			Catalog temp = new Catalog();
			temp.setName(file.getName());
			temp.setSpread(false);
			temp.setPath(file.getPath());
			temp.setId(id++);
			if(file.isDirectory()){
				temp.setDir(true);
				iteratorChildFile(file.listFiles(), temp);
			}else{
				if(!file.getName().endsWith("md")){
					continue;
				}
			}
			catalog.getChildren().add(temp);
		}
		return catalog;
	}

}
